<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-30 11:43:25
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-04-24 10:30:36
-->
<template>
	<div>
		<el-input v-model="query" placeholder="请输入菜单名称" @input="onQueryChanged" />
		<el-tree-v2
			class="mt10"
			v-bind="$attrs"
			ref="treeRef"
			node-key="id"
			:expand-on-click-node="false"
			highlight-current
			show-checkbox
			:data="treeData"
			:props="defaultProps"
			:filter-method="filterMethod"
			:height="350"
		>
			<template #default="{ node, data }">
				<span>
					{{ node.label }}
					<span v-if="data.type == 1" class="text-auth-tag">权限</span>
				</span>
			</template>
		</el-tree-v2>
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod/index'
const emit = defineEmits(['tree-load'])
const query = ref('')
const treeData = ref([])
const treeRef = ref()
const props = defineProps({
	deviceType: [String, Number],
	roleValue: [String, Number],
	api: [String, Number],
})
const defaultProps = {
	value: 'id',
	label: 'label',
	children: 'children',
}
const onQueryChanged = (query: string) => {
	treeRef.value!.filter(query)
}
const filterMethod = (value: string, data: any) => {
	if (!value) return true
	const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
	if (reg.test(value)) {
		return data.label.includes(value)
	} else {
    const name = data.permission?data.permission:data.label
		return name.includes(value)
	}
}
const getCheckedKeys = () => {
	const checkedKeys = treeRef.value!.getCheckedKeys(false)
	const checkedSelfKeys = treeRef.value!.getHalfCheckedKeys()
	return [...checkedSelfKeys, ...checkedKeys]
}
const setCheckedKeys = (data) => {
	if (data && Array.isArray(data)) {
		data.map((key) => {
			const node = treeRef.value!.getNode(key)
			if (node.isLeaf) {
				treeRef.value!.setChecked(key, true)
			}
		})
	}
}

const getInitData = () => {
	apiMod[props.api]({
		deviceType: props.deviceType,
		roleIds: props.roleValue,
	}).then((res) => {
		treeData.value = res.data
    // 默认展开第一层
		// const keys = res.data.map((item) => item.id)
		// treeRef.value!.setExpandedKeys([...keys, -1])

		emit('tree-load', res.data)
	})
}

onMounted(() => {
	getInitData()
})
defineExpose({
	getCheckedKeys,
	setCheckedKeys,
})
</script>

<style scoped>
.text-auth-tag {
	font-size: 10px;
	color: #fff;
	background: var(--el-color-primary);
	padding: 2px 4px;
	border-radius: 20px;
}
</style>
